package com.atguigu.dga.governance.assessor.quality;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.constant.DgaConstant;
import com.atguigu.dga.dolphinscheduler.bean.TDsTaskInstance;
import com.atguigu.dga.dolphinscheduler.service.TDsTaskInstanceService;
import com.atguigu.dga.governance.assessor.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * ClassName: TableProduceTimelinessAssessor
 * Package: com.atguigu.dga.governance.assessor.quality
 * Description:
 *
 * @Author:
 * @Create: 2024/3/20 11:17
 * @Version: 1.0
 */
@Component("TABLE_PRODUCE_TIMELINESS")
public class TableProduceTimelinessAssessor extends Assessor {
    @Autowired
    TDsTaskInstanceService tDsTaskInstanceService;
    @Override
    public void checkProblem(AssessParam assessParam, GovernanceAssessDetail governanceAssessDetail) throws ParseException, URISyntaxException, IOException, InterruptedException {
        // 计算考评日期当日的产出时效， 前days天平均产出时效，是否超过指标参数
        // TODO 跳过ODS表（load data 没有任务实例）
        if(DgaConstant.DW_LEVEL_ODS.equals(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTableName())) {
            return;
        }

        String metricParamsJson = assessParam.getGovernanceMetric().getMetricParamsJson();
        JSONObject paramJsonObj = JSON.parseObject(metricParamsJson);
        Integer paramDays = paramJsonObj.getInteger("days");
        Integer paramPercent = paramJsonObj.getInteger("percent");

        // TODO 当日时效 毫秒级
        TDsTaskInstance tDsTaskInstance = assessParam.getTDsTaskInstance();
        if(tDsTaskInstance == null) {
            return;
        }
        Date endTimeDate = tDsTaskInstance.getEndTime();
        Date startTimeDate = tDsTaskInstance.getStartTime();

        Long currProduceTime = endTimeDate.getTime() - startTimeDate.getTime();

        // TODO 前days天 平均产出时效 循环 或者 sql(找到最早哪天 前days天实例)
        // 从数据库查出前days天的实例
        String assessDateStr = assessParam.getAssessDate();
        Date assessDate = DateUtils.parseDate(assessDateStr, "yyyy-MM-dd");
        Date beforeDaysDate = DateUtils.addDays(assessDate, -paramDays);
        String beforeDaysDateStr = DateFormatUtils.format(beforeDaysDate, "yyyy-MM-dd");

        // 任务实例S层封装方法
        String name = assessParam.getTableMetaInfo().getSchemaName() + "." + assessParam.getTableMetaInfo().getTableName();
        List<TDsTaskInstance> beforeDaysInstanceList =
                tDsTaskInstanceService.getBeforeDaysInstanceList(name, assessDateStr, beforeDaysDateStr);

        Long totalProduceTime = 0L;

        // 循环返回的集合
        for (TDsTaskInstance dsTaskInstance : beforeDaysInstanceList) {
            totalProduceTime += (dsTaskInstance.getEndTime().getTime() - dsTaskInstance.getStartTime().getTime());
        }

        // 判断有前几天 求平均
        if(totalProduceTime != 0L) {
            Long avgProduceTime = totalProduceTime / beforeDaysInstanceList.size();
            // 判断是否超过percent
            if((currProduceTime - avgProduceTime) * 100 / avgProduceTime > paramPercent) {
                governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
                governanceAssessDetail.setAssessProblem("当日产出时效超过前" + paramDays + "天平均产出时效的" + paramPercent + "%");
                governanceAssessDetail.setAssessComment("当日产出时效：" + currProduceTime + ", 前" + beforeDaysInstanceList.size() + "天的平均产出时效：" + avgProduceTime);
            }
        }



    }
}
